﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using MusicHouse.Models;
using MusicHouse.Models.Views;

namespace MusicHouse.Util
{
    public static class Funcoes
    {
        public static casamusicaEntities1 Db
        {
            get { return new casamusicaEntities1(); }
        }

        #region TamanhoPagina

        public static int TamanhoPagina
        {
            get
            {
                try
                {
                    return int.Parse(ConfigurationManager.AppSettings["TotalProdPorPagina"] ?? "10");
                }
                catch 
                {
                    return 10;
                }
            }
        }

        #endregion

        #region TotalPaginas

        public static int TotalPaginas(int totalRegs)
        {
            int totalPaginas = totalRegs / TamanhoPagina;
            if ((totalPaginas % TamanhoPagina) > 0)
                totalPaginas++;
            return totalPaginas;
        }

        #endregion
        
        #region Pagina

        public static IQueryable<T> Pagina<T, TResult>(this IQueryable<T> obj, int page, int pageSize, Expression<Func<T, TResult>> orderSelector, bool asc)//, out int rowsCount)
        {
            //rowsCount = obj.Count();
            int innerRows = (page - 1) * pageSize;
            if (asc)
            {
                if (orderSelector != null) return obj.OrderBy(orderSelector).Skip(innerRows).Take(pageSize).AsQueryable();
            }
            else
            {
                if (orderSelector != null)
                    return obj.OrderByDescending(orderSelector).Skip(innerRows).Take(pageSize).AsQueryable();
            }

            return obj.Skip(innerRows).Take(pageSize).AsQueryable();
        }

        #endregion

        #region RetornarListaPaginacao

        public static IList<Paginacao> RetornarListaPaginacao(int totalReg, string currentActionName, string currentControllerName,int paginaAtual )
        {
            IList<Paginacao> paginas = new List<Paginacao>();
            int totalPg = TotalPaginas(totalReg);
            for (var i = 1; i <= totalPg; i++)
            {

                paginas.Add(new Paginacao
                                {
                                    ActionName = currentActionName,
                                    ControllerName = currentControllerName,
                                    Pagina = i.ToString(),
                                    IsAtual = i == paginaAtual

                                });
            }
            return paginas;
        }

        #endregion

    }
}